package controller

import (
	"awesomeProject/Response"
	"awesomeProject/dao"
	"awesomeProject/forms"
	"awesomeProject/models"
	"awesomeProject/utils"
	"github.com/gin-gonic/gin"
)

func PasswordLogin(c *gin.Context) {
	PasswordLoginForm := forms.PasswordLoginForm{}

	if err := c.ShouldBind(&PasswordLoginForm); err != nil {
		// color.Blue(err.Error())
		utils.HandleValidatorError(c, err)
		return
	}
	//if !store.Verify(PasswordLoginForm.CaptchaId, PasswordLoginForm.Captcha, true) {
	//	Response.Err(c, 400, 400, "captcha error", "")
	//	return
	//}

	user, ok := dao.FindUserInfo(PasswordLoginForm.Username, PasswordLoginForm.Password)
	if !ok {
		Response.Err(c, 401, 401, "用户未注册或密码错误", "")
		return
	}
	token := utils.CreateToken(c, user.AdminUserId, user.NickName, user.Locked)
	userinfoMap := HandleUserModelTopMap(user)
	userinfoMap["token"] = token
	Response.Success(c, 200, "success", userinfoMap)
}

func HandleUserModelTopMap(user *models.User) map[string]interface{} {
	userItemMap := map[string]interface{} {
		"id": user.AdminUserId,
		"username": user.LoginUserName,
		"nick_name":user.NickName,
	}
	return userItemMap
}